﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using FatHibernation.Utilities.DesignByContract;
using NHibernate;

namespace FatHibernation.Data
{
    public class DataContextStorage
    {

        private const string SESSIONKEY = "SESSIONKEY";
        private const string TRANSACTIONKEY = "TRANSACTIONKEY";


        [ThreadStatic]
        private static IDictionary _itemsOverride = null;

        private static IDictionary Items
        {
            get
            {
                Check.Require(HttpContext.Current != null || _itemsOverride != null, "Items must be overridden when HttpContext is null!");
                
                if (_itemsOverride == null)
                    return HttpContext.Current.Items;
                return _itemsOverride;
            }
        }

        public static void OverrideHttpContextItems()
        {
            _itemsOverride = new Dictionary<string, object>();
        }

        

        public static ISession Session
        {
            get
            {
                return (ISession) Items[SESSIONKEY];
            }
            set
            {
                Items[SESSIONKEY] = value;
            }
        }

        public static ITransaction CurrentTransaction
        {
            get
            {
                return (ITransaction) Items[TRANSACTIONKEY];
            }
            set
            {
                Items[TRANSACTIONKEY] = value;
            }
        }

        public static void ClearSession()
        {
            Items.Remove(SESSIONKEY);
        }
        public static void ClearTransaction()
        {
            Items.Remove(TRANSACTIONKEY);
        }
    }
}
